package client_commands;

import utils.Constants;
import client.ClientApplication;
import client.ClientBindObject;
import client_tree.User;

public class SERV_LOGOUTCommand extends Command {

	
	public SERV_LOGOUTCommand(String parameter) {
		setCode(SERV_LOGOUT_CMD);
		setParameter(parameter);
	}
	
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {

		String username = getParameter();
		
		if (username.equalsIgnoreCase(Constants.LOGOUT_SEQUENCE)){
//			theApp.retrieveSocketConnection().simulateLogout();
			return true;
		}
		
		int status = OFFLINE_STATUS;

		User user = theApp.getClientModel().getOnlineModel().getUserByUsername(username);
		
		// null je ako se user izlogovao, a da je njegov status bio invisible
		if (user == null) {
			user = theApp.getClientModel().getOfflineModel().getUserByUsername(username);
		}
		
		if (user == null)
			return true;
		
		user.setStatus(status);
		
		theApp.getClientModel().addUser(user);
		
		
		if ( ClientApplication.clientBinding.get(username) != null ) {
			
			ClientBindObject cbo = ClientApplication.clientBinding.get(username);
			if (cbo.getDialog() != null) {
				cbo.getDialog().setConnection(null);
				cbo.getDialog().setSendButtonRights(false);
				cbo.getDialog().stopTypingListener();
			}
			
			// sada ne mora - reseno je u quitConnection() sa shutdownInput(), shutdownOutput()
//			cbo.getConnection().writeData( Long.toString(cbo.getConnection().getConnectionID()) );
			
//			try {
//				Thread.sleep(2000);
//			}
//			catch (InterruptedException ie) {
//				ie.printStackTrace();
//			}
			
			if (cbo.getConnection() != null)
				cbo.getConnection().quitConnection();
			
			cbo.setConnection(null);
			
			if (cbo.isDialogOpen() == false) {
				ClientApplication.clientBinding.remove(username);
			}
			
			if ( cbo.getCall() != null ) {
//				cbo.getCall().setAudioEstablished(false);
//				cbo.getCall().setVideoEstablished(false);
				cbo.getCall().hangUpCall();
				cbo.getDialog().getStreamingPanel().removeListeners();
				cbo.setCall(null);
			}
		}

		
		return true;
	}
}
